package utils

import (
	"fmt"
	"go_cms/app/model"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DbEngin *Db

type Db struct {
	*gorm.DB
}

// 初始化数据库连接
func InitDB(cfg *Config) (err error) {
	// 数据库信息
	dbcfg:=cfg.Database
	dsn:=fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		dbcfg.User,
		dbcfg.Password,
		dbcfg.Host,
		dbcfg.Port,
		dbcfg.DbName)
	fmt.Println(dsn)
	// 连接数据库
	//DbE, err := gorm.Open("mysql", dsn)
	DbE, err := gorm.Open(mysql.Open(dsn),&gorm.Config{
		//Logger:logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		fmt.Printf("initdb.go 30 open %s failed, err:%v\n", err)
		return
	}


	DbE.AutoMigrate(&model.User{},&model.Role{},&model.Department{},&model.Menu{},&model.Good{},&model.Category{})

	db := new(Db)
	db.DB=DbE
	DbEngin = db
	return
}
